<template>
  <div class="demo-collapse" v-if="t !== '2'">
    <div style="height: 400px; overflow: auto">
      <el-tabs v-model="activeName2" class="demo-tabs">
        <el-tab-pane label="上传" name="first">
          <el-row>
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                :http-request="UploadOss"
                :before-upload="beforeUploadVideoOss"
                :show-file-list="false"
                accept=".mp4,.mov,.avi,.wmv,.mkv,.flv"
              >
                <div class="p-2 m-2 shadow-lg hover:border-1 hover:border-yellow-500">
                  <img
                    :src="getSettingbyKey(`图文视频`)"
                    mode="scaleToFill"
                    style="width: 30px; height: 30px; margin: 0 auto; margin-top: 10px"
                  />
                  <div class="mt-2 text-center">视频</div>
                </div>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                :http-request="UploadOss"
                :before-upload="beforeUploadAuidoOss"
                :show-file-list="false"
                accept=".mp3,.wav,.aac,.ogg,.flac"
              >
                <div class="p-2 m-2 shadow-lg border-1 border-white hover:border-1 hover:border-yellow-500">
                  <img
                    :src="getSettingbyKey(`图文音频`)"
                    mode="scaleToFill"
                    style="width: 30px; height: 30px; margin: 0 auto; margin-top: 10px"
                  />
                  <div class="mt-2 text-center">音频</div>
                </div>
              </el-upload>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                :http-request="UploadOss"
                :before-upload="beforeUploadImageOss"
                :show-file-list="false"
                accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff"
              >
                <div class="p-2 m-2 shadow-lg border-1 border-white hover:border-1 hover:border-yellow-500">
                  <img
                    :src="getSettingbyKey(`图文图片`)"
                    mode="scaleToFill"
                    style="width: 30px; height: 30px; margin: 0 auto; margin-top: 10px"
                  />
                  <div class="mt-2 text-center">图片</div>
                </div>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <div
                class="p-2 m-2 shadow-lg border-1 border-white hover:border-1 hover:border-yellow-500"
                @click="
                  filelist = [];
                  dialogVisible = true;
                "
              >
                <img
                  :src="getSettingbyKey(`图文图片`)"
                  mode="scaleToFill"
                  style="width: 30px; height: 30px; margin: 0 auto; margin-top: 10px"
                />
                <div class="mt-2 text-center">轮播</div>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-upload
                class="upload-demo"
                :http-request="UploadOss"
                :before-upload="beforeUploadIFileOss"
                :show-file-list="false"
                accept=".doc,.docx,.pdf,.xlsx,.zip"
              >
                <div class="p-2 m-2 shadow-lg border-1 border-white hover:border-1 hover:border-yellow-500">
                  <img
                    :src="getSettingbyKey(`图文文件`)"
                    mode="scaleToFill"
                    style="width: 30px; height: 30px; margin: 0 auto; margin-top: 10px"
                  />
                  <div class="mt-2 text-center">文件</div>
                </div>
              </el-upload>
            </el-col>
            <el-col :span="12">
              <div
                class="p-2 m-2 shadow-lg border-1 border-white hover:border-1 hover:border-yellow-500"
                @click="
                  textarea1 = '';
                  dialogVisible2 = true;
                "
              >
                <img
                  :src="getSettingbyKey(`图文文本`)"
                  mode="scaleToFill"
                  style="width: 30px; height: 30px; margin: 0 auto; margin-top: 10px"
                />
                <div class="mt-2 text-center">文字</div>
              </div>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="标题" name="second">
          <div>
            <div
              v-for="value in 18"
              :key="value"
              :class="`title  title${value} mt-10`"
              data-text="亿码互联"
              @click="addtitle(value)"
            >
              亿码互联
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="分割线" name="third">
          <div>
            <div v-for="value in linelist" :key="value" @click="addline(value)">
              <hr :class="`${value} mt-10`" />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-collapse v-model="activeName">
      <el-collapse-item name="1">
        <div>
          <div v-for="(form, index) in Formlist" :key="index" class="p-1">
            <div class="border p-2">
              {{ form.title }}
            </div>
            <div class="mt-4">
              <el-row :gutter="12">
                <el-col
                  :span="8"
                  v-for="(item, i) in form.items"
                  :key="i"
                  class="p-4"
                  custom-style="padding:20rpx"
                  @click="click(index, item)"
                >
                  <div style="text-align: center">
                    <img :src="item.img" mode="scaleToFill" class="w-6 h-6" style="margin: 0 auto" />
                    <text class="grid-text mt-2">
                      {{ item.title }}
                    </text>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </div>
      </el-collapse-item>
      <!-- <el-collapse-item title="分割线" name="3">
        <div>

        </div>
      </el-collapse-item> -->
    </el-collapse>
    <el-dialog v-model="dialogVisible" width="500" :before-close="handleClose">
      <div>
        <el-upload
          class="upload-demo"
          drag
          multiple
          :file-list="filelist"
          :http-request="UploadOss"
          :on-remove="removeFile"
          :before-upload="beforeUploadICarouselOss"
          list-type="picture-card"
          accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff"
        >
          <img
            :src="getSettingbyKey('图文添加')"
            mode="scaleToFill"
            style="width: 25px; height: 25px; margin: 0 auto"
          />
        </el-upload>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="lb()"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible2" width="800" :before-close="handleClose">
      <editor v-model="textarea1" :init="init" :tinymceScriptSrc="tinymceScriptSrc"></editor>
      <!-- <vue3-tinymce v-model="textarea1" :setting="state.setting" /> -->
      <!-- <div>
        <el-input v-model="textarea1" style="width: 100%" type="textarea" rows="8"
          :autosize="{ minRows: 8, maxRows: 20 }" placeholder="请在此处输入文字" />
      </div> -->
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-switch v-model="value" size="large" active-text="居中" inactive-text="居左" class="float-left" /> -->
          <el-button @click="dialogVisible2 = false">取消</el-button>
          <el-button type="primary" @click="wz()"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible3" width="1200" :before-close="handleClose">
      <el-row>
        <el-col :span="8" v-for="card in cardlist" :key="card.id" class="p-2">
          <div
            class="rounded-4 shadow-light border hover:border-yellow-500"
            style="position: relative; width: 100%; height: 200px"
            :style="{
              background: `url(${card.obj.bg})`,
              'background-repeat': 'no-repeat',
              'background-size': '100% 100%',
            }"
            @click="openitem(card)"
          >
            <div style="position: absolute; top: 30px; right: 30px">
              <img :src="card.obj.avatar" mode="scaleToFill" class="w-16 h-16 rounded-full" />
            </div>
            <div style="position: absolute; top: 30px; left: 30px; font-weight: 800" class="text-2xl">
              {{ card.obj.name }}
            </div>
            <div style="position: absolute; top: 70px; left: 30px" class="text-xl">
              {{ card.obj.phone }}
            </div>
            <div style="position: absolute; bottom: 20px; left: 30px" class="text-lg">
              {{ card.obj.companyname }}
            </div>
            <div v-if="card.obj.department" style="position: absolute; top: 120px; left: 30px" class="text-sm">
              {{ card.obj.department }} | {{ card.obj.position }}
            </div>
          </div>
          <div class="text-center mt-2">{{ card.eqCreatedTime }}</div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
  <div v-else>
    <div v-for="(item, index) in bglist" :key="index" class="p-2">
      <img
        :src="item.image"
        class="m-1"
        style="width: 100%; height: auto"
        :class="{ selected: isSelected(index) }"
        @click="selectImage(index)"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits } from 'vue';
import { getSettingbyKey, getSettingbyincludes } from '@/utils/index.js';
import {
  fileput,
  type,
  formatBytes,
  beforeUploadVideoOss,
  beforeUploadAuidoOss,
  beforeUploadImageOss,
  beforeUploadIFileOss,
  beforeUploadICarouselOss,
} from '@/utils/ali-oss';
import moment from 'moment';
import Vue3Tinymce from '@jsdawn/vue3-tinymce';
import { useRoute, useRouter } from 'vue-router';
import { getQrcodebytype, qrcode_one } from '@/api/index.js';

import tinymce from 'tinymce/tinymce'; //tinymce默认hidden，不引入不显示
import Editor from '@tinymce/tinymce-vue';
import 'tinymce/themes/silver/theme'; // 主题文件
import 'tinymce/icons/default';
import 'tinymce/models/dom';
// tinymce插件可按自己的需要进行导入
import 'tinymce/plugins/accordion'; // 列表插件
import 'tinymce/plugins/lists'; // 列表插件
import 'tinymce/plugins/advlist'; // 有序列表插件
import 'tinymce/plugins/autolink'; // 当用户输入有效的完整URL时，autolink插件会自动创建超链接。
import 'tinymce/plugins/link'; // 链接
import 'tinymce/plugins/autosave'; // 定时自动将编辑内容保存到浏览器本地存储中（Local Storage）
import 'tinymce/plugins/autoresize'; // 可拉伸宽度
import 'tinymce/plugins/charmap'; // 特殊字符
import 'tinymce/plugins/code'; // 查看源码
import 'tinymce/plugins/codesample'; // 插入代码
import 'tinymce/plugins/directionality'; // 文字方向
import 'tinymce/plugins/emoticons'; // 表情符号
import 'tinymce/plugins/emoticons/js/emojis';
import 'tinymce/plugins/fullscreen'; //全屏
import 'tinymce/plugins/image'; // 插入上传图片插件
import 'tinymce/plugins/importcss'; //引入自己定义的css文件
import 'tinymce/plugins/insertdatetime'; //插入时间日期
import 'tinymce/plugins/nonbreaking'; // 空格
import 'tinymce/plugins/pagebreak'; //分页
import 'tinymce/plugins/preview'; // 预览
import 'tinymce/plugins/quickbars'; // 快速工具栏
import 'tinymce/plugins/save'; // 保存
import 'tinymce/plugins/searchreplace'; //查询替换
import 'tinymce/plugins/table'; // 插入表格插件
import 'tinymce/plugins/wordcount'; // 字数统计插件
import 'tinymce/plugins/visualblocks'; // 块范围显示

const tinymceScriptSrc = '/tinymce/tinymce.min.js';
const init = {
  height: 400,
  language_url: '/tinymce/langs/zh-Hans.js',
  language: 'zh-Hans',
  skin_url: '/tinymce/skins/ui/oxide', // 皮肤：这里引入的是public下的资源文件
  // skin_url: 'tinymce/skins/ui/oxide-dark',//黑色系
  content_css: '/tinymce/skins/content/default/content.css', //内容区域css样式
  content_style: 'p {margin: 5px 0;}',
  plugins:
    ' accordion lists advlist quickbars autolink link autosave charmap wordcount code codesample directionality emoticons fullscreen image importcss insertdatetime nonbreaking pagebreak preview searchreplace table visualblocks formatpainter kityformula-editor',
  toolbar: ` undo redo  code pastetext formatpainter removeformat fullscreen wordcount  visualblocks |   blocks fontfamily fontsize forecolor backcolor bold italic underline strikethrough lineheight | alignleft alignright aligncenter alignjustify
  outdent indent ltr rtl | bullist numlist | blockquote subscript superscript  table image charmap emoticons hr  pagebreak  | insertdatetime  |  custom-btn`,
  toolbar_mode: 'wrap', // 工具栏模式: floating sliding scrolling wrap
  external_plugins: {
    // 引入自定义的插件
    'kityformula-editor': '/tinymce/plugins/kityformula-editor/plugin.min.js',
    formatpainter: '/tinymce/plugins/formatpainter/plugin.min.js',
  },
  menubar: true, // 菜单栏
  statusbar: true, // 是否显示底部状态栏
  auto_focus: true, // 自动聚焦
  branding: false, // 默认会在右下角显示Tiny图标
  promotion: false, // 隐藏upgrade按钮
  resize: true, // 改变宽高
  // 快速工具栏配置，需引入插件 quickbars
  quickbars_selection_toolbar: 'bold italic underline strikethrough', // 设置 快速选择 触发提供的工具栏 需引入插件  默认 'alignleft aligncenter alignright' 设置为false禁用
  quickbars_insert_toolbar: 'quickimage quicktable quicklink', // 设置 快速插入 触发提供的工具栏 需引入插件quickbars 默认 quickimage quicktable 设置为false禁用
  quickbars_image_toolbar: 'alignleft aligncenter alignright',
  save_onsavecallback: function () {
    alert('已保存');
  },
  automatic_uploads: false, // 禁止图片自动上传
  font_size_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
  font_family_formats:
    '微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;',
  setup: (editor) => {
    console.log(editor);
    editor.ui.registry.addButton('custom-btn', {
      text: '背景段落',
      icon: 'ai',
      tooltip: '背景段落',
      onAction: function () {
        uploadImage(editor);
      },
    });
    const onAction = (autocompleteApi, rng, value) => {
      editor.selection.setRng(rng);
      // editor.insertContent(value);
      // contenteditable=false 不可编辑，保证删除时#和内容为一个整体
      editor.insertContent(`<span style="color: blue;" contenteditable="false">#${value}</span><span>&nbsp;</span>`);
      autocompleteApi.hide();
    };

    const getMatchedChars = (pattern) => {
      return specialChars.filter((char) => char.text.indexOf(pattern) !== -1);
    };
    /* 自动补全 */
    editor.ui.registry.addAutocompleter('specialchars_cardmenuitems', {
      trigger: '#',
      minChars: 0,
      columns: 1,
      highlightOn: ['char_name'],
      onAction: onAction,
      fetch: (pattern) => {
        return new Promise((resolve) => {
          const results = getMatchedChars(pattern).map((char) => ({
            type: 'cardmenuitem',
            value: char.value,
            label: char.text,
            items: [
              {
                type: 'cardcontainer',
                direction: 'vertical',
                items: [
                  {
                    type: 'cardtext',
                    text: char.text,
                    name: 'char_name',
                  },
                  {
                    type: 'cardtext',
                    text: char.value,
                  },
                ],
              },
            ],
          }));
          resolve(results);
        });
      },
    });
  },

  // 此处为自定义图片上传处理函数
  images_upload_handler: (blobInfo) =>
    new Promise((resolve, reject) => {
      let file = blobInfo.blob();
      // 调接口
      console.log(file, resolve, reject, '==file');
      // let url = 'blob:http://127.0.0.1:8000/2c6c7bbe-cb9a-481d-acfe-adc00f2866d5'
      // resolve(url)
    }),
  image_advtab: true, // 图片高级功能
  lists_indent_on_tab: true, // 是否按tab键进入新的子列表
  link_context_toolbar: true,
  link_rel_list: [
    { title: 'No Referrer', value: 'noreferrer' },
    { title: 'External Link', value: 'external' },
  ],
  link_target_list: [
    { title: 'None', value: '' },
    { title: 'Same page', value: '_self' },
    { title: 'New page', value: '_blank' },
    { title: 'Parent frame', value: '_parent' },
  ],
  fullscreen_native: true,
  pagebreak_split_block: true,
  table_border_widths: [
    { title: 'small', value: '1px' },
    { title: 'medium', value: '3px' },
    { title: 'large', value: '5px' },
  ],
  table_toolbar:
    'tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol tablecellborderwidth tablecellborderstyle',
};

const route = useRoute();
const t = route.query.t;
const mode = route.query.mode;
const state = reactive({
  content: 'hello vue3-tinymce!',
  // editor 配置项
  setting: {
    height: 300,
    toolbar:
      'undo redo | fullscreen | blocks fontfamily fontsize | forecolor backcolor alignleft aligncenter alignright alignjustify | numlist bullist | image media table  | bold italic underline strikethrough charmap| indent outdent | superscript subscript | removeformat | myCustomToolbarButton | code',
    toolbar_mode: 'sliding',
    quickbars_selection_toolbar: 'removeformat | bold italic underline strikethrough | fontsize forecolor backcolor',
    plugins:
      'link image imagetools table lists advlist fullscreen quickbars importword layout bbcode code charmap media',
    font_size_formats: '12px 14px 16px 18px',
    link_default_target: '_blank',
    link_title: false,
    nonbreaking_force_tab: true,
    // 以中文简体为例
    language: 'zh-Hans',
    language_url: '/tinymce/langs/zh-Hans.js',
    branding: false,
    setup: function (editor) {
      editor.ui.registry.addButton('myCustomToolbarButton', {
        text: '123',

        onAction: function () {
          // 调用上传图片的函数
          uploadImage(editor);
        },
      });
    },
  },
});
// 上传图片函数
function uploadImage(editor) {
  var fileInput = document.createElement('input');
  fileInput.setAttribute('type', 'file');
  fileInput.setAttribute('accept', 'image/*');
  fileInput.onchange = function (e) {
    var file = e.target.files[0];
    console.log('file', file);
    var reader = new FileReader();

    reader.onload = function (e) {
      var imageUrl = e.target.result;

      const img = new Image();
      img.src = e.target.result;
      img.onload = () => {
        const imageWidth = img.width;
        const imageHeight = img.height;
        console.log(imageWidth, imageHeight);
        // 将图片URL设置为div的背景
        var div = document.createElement('div');
        div.style.backgroundImage = 'url(' + imageUrl + ')';
        div.style.width = img.width + 'px';
        div.style.height = img.height + 'px';
        div.style.backgroundSize = 'cover';
        div.style.backgroundRepeat = 'no-repeat'; // 设置背景不重复
        document.body.appendChild(div);
        //let divstr = `<div style="background:url(${imageUrl});width:${img.width};height:${img.height};background-size:cover;background-repeat:no-repeat"></div>`

        // 将div插入到编辑器中
        editor.insertContent(div.outerHTML);
        document.body.removeChild(div);
      };
    };

    reader.readAsDataURL(file);
  };
  fileInput.click();
}

import { useListStore } from '@/stores/list';
const listStore = useListStore();
if (mode === 'v2') {
  listStore.setList([]);
}
//const list = listStore.list;
const list = computed(() => listStore.list);
if (t === '2') {
  list.card = {
    avatar: getSettingbyKey('默认头像'),
    bg: '',
    name: '',
    phone: '',
    weixin: '',
    email: '',
    companyname: '',
    department: '',
    position: '',
    address: '',
    longitude: 0,
    latitude: 0,
  };
  listStore.setList(list);
  console.log('card end');
}
const emit = defineEmits(['clickChild']);
const dialogVisible = ref(false);
const dialogVisible2 = ref(false);
const dialogVisible3 = ref(false);
const textarea1 = ref('');
const value = ref(false);
const activeName = ref('1');
const filelist = ref([]);
const cardlist = ref([]);
const titlelist = getSettingbyincludes('tw_title');
const linelist = [
  'hr-solid',
  'hr-dotted',
  'hr-dotted2',
  'hr-dashed',
  'hr-dashed2',
  'hr-dashed-fixed',
  'hr-double',
  'hr-edge-weak',
  'hr-twill',
  'hr-wavy',
  'hr-shadow',
];
const bglist = ref([
  { image: getSettingbyKey('名片背景1') },
  { image: getSettingbyKey('名片背景2') },
  { image: getSettingbyKey('名片背景3') },
  { image: getSettingbyKey('名片背景4') },
  { image: getSettingbyKey('名片背景5') },
  { image: getSettingbyKey('名片背景6') },
  { image: getSettingbyKey('名片背景7') },
]);
const selectedIndex = ref(0);
function isSelected(index) {
  return selectedIndex.value === index;
}
function selectImage(index) {
  if (selectedIndex.value === index) {
    selectedIndex.value = null; // 如果已经选中了该图片，则取消选中
    list.card.bg = null;
  } else {
    selectedIndex.value = index; // 选择该图片
    list.card.bg = bglist.value[selectedIndex.value].image;
  }
}
const activeName2 = ref('first');
const showToast = inject('$showToast');

const Formlist = ref([
  {
    title: '基础表单',
    items: [
      {
        title: '单行文本',
        img: getSettingbyKey('表单单行文本'),
      },
      {
        title: '多行文本',
        img: getSettingbyKey('表单多行文本'),
      },
      {
        title: '数字',
        img: getSettingbyKey('表单数字'),
      },
      {
        title: '日期',
        img: getSettingbyKey('表单日期'),
      },
      {
        title: '时间',
        img: getSettingbyKey('表单时间'),
      },
      {
        title: '单选项',
        img: getSettingbyKey('表单单选项'),
      },
      {
        title: '多选项',
        img: getSettingbyKey('表单多选项'),
      },
      {
        title: '检查项',
        img: getSettingbyKey('表单检查项'),
      },
      {
        title: '定位',
        img: getSettingbyKey('表单定位'),
      },
      {
        title: '地址',
        img: getSettingbyKey('表单地址'),
      },
      {
        title: '表格',
        img: getSettingbyKey('表单表格'),
      },
      {
        title: '自增表格',
        img: getSettingbyKey('表单自增表格'),
      },
      {
        title: 'NPS量表',
        img: getSettingbyKey('表单NPS量表'),
      },
      {
        title: '评价',
        img: getSettingbyKey('表单评分'),
      },
      {
        title: '分组标题',
        img: getSettingbyKey('表单分组标题'),
      },
      {
        title: '手写签名',
        img: getSettingbyKey('表单手写签名'),
      },
    ],
  },
  {
    title: '多媒体类',
    items: [
      {
        title: '上传图片',
        img: getSettingbyKey('表单上传图片'),
      },
      {
        title: '上传视频',
        img: getSettingbyKey('表单上传视频'),
      },
    ],
  },
  {
    title: '个人信息',
    items: [
      {
        title: '姓名',
        img: getSettingbyKey('表单姓名'),
      },
      {
        title: '手机号',
        img: getSettingbyKey('表单手机号'),
      },
      {
        title: '身份证',
        img: getSettingbyKey('表单身份证'),
      },
      {
        title: '性别',
        img: getSettingbyKey('表单性别'),
      },
      {
        title: '年龄',
        img: getSettingbyKey('表单年龄'),
      },
      {
        title: '工号',
        img: getSettingbyKey('表单工号'),
      },
      {
        title: '车牌',
        img: getSettingbyKey('表单工号'),
      },
      {
        title: '名片',
        img: getSettingbyKey('表单名片'),
      },
    ],
  },
]);
//判断尺寸方法
function getImageSize(imageUrl) {
  return new Promise((resolve, reject) => {
    // 创建一个临时的 img 元素
    const img = new Image();

    img.src = imageUrl;

    // 监听 load 事件，当图片加载完成后获取宽高
    img.onload = () => {
      // 根据图片的宽高比返回不同的值
      if (img.width >= img.height) {
        resolve('aspectFill');
      } else {
        resolve('widthFix');
      }
    };

    // 监听 error 事件，处理加载错误的情况
    img.onerror = () => {
      reject(new Error('图片加载失败，请检查图片地址是否正确。'));
    };
  });
}
function getVideoSize(videoUrl) {
  return new Promise((resolve, reject) => {
    // 创建一个临时的 video 元素
    const video = document.createElement('video');

    // 设置 video 元素的 src 属性
    video.src = videoUrl;

    // 监听 loadedmetadata 事件，当视频元数据加载完成后获取宽高
    video.addEventListener('loadedmetadata', () => {
      // 根据视频的宽高比返回不同的值
      if (video.videoWidth >= video.videoHeight) {
        resolve('aspect-16/9');
      } else {
        resolve('aspect-9/16');
      }
    });
  });
}

async function UploadOss(option) {
  console.log(option, type.value);
  let objName = option.file.name;
  let fileName = moment().format('YYYY/MM/DD');
  //this.uploadLoading = true
  fileput(`pc/${fileName}/${objName}`, option.file)
    .then(async (res) => {
      console.log(res);
      if (res.res.statusCode === 200) {
        console.log('上传成功');
        if (type.value !== '滚动') {
          showToast('上传' + type.value + '成功', 'success');
          const d = {
            key: type.value,
            name: res.name.split('/')[res.name.split('/').length - 1],
            value: res.url,
            grid: 'w-full',
          };
          if (type.value === '图片') {
            await getImageSize(res.url)
              .then((result) => {
                d.mode = result;
              })
              .catch((error) => {
                console.error(error);
              });
          } else if (type.value === '视频') {
            await getVideoSize(res.url)
              .then((result) => {
                d.mode = result;
              })
              .catch((error) => {
                console.error(error);
              });
          }
          //emit('clickChild', d);

          if (mode === 'v1') {
            console.log('list1', list.mdata);
            list.value.mdata.push(d);
          } else if (mode === 'v2') {
            list.value.push(d);
          }
          listStore.setList(list);
          console.log('list2', list);
        } else {
          filelist.value.push(res);
        }
      } else {
        console.log('上传失败');
      }
    })
    .catch((err) => {
      showToast('上传文件异常:' + err, 'error');
    });
}
function lb() {
  console.log('filelist', filelist.value);
  const d = {
    key: type.value,
    name: '图片轮播',
    value: filelist.value.map((file) => file.url),
    grid: 'w-full',
  };
  if (mode === 'v1') {
    list.value.mdata.push(d);
  } else if (mode === 'v2') {
    list.value.push(d);
  }
  listStore.setList(list);
  dialogVisible.value = false;
}
function wz() {
  const d = {
    key: '文本',
    value: this.textarea1,
    center: 'text-left',
    grid: 'w-full',
  };
  console.log('value.value', value.value);
  if (value.value) {
    d.center = 'text-center';
  }
  console.log('d', d);
  if (mode === 'v1') {
    list.value.mdata.push(d);
  } else if (mode === 'v2') {
    list.value.push(d);
  }
  //listStore.setList(list);
  dialogVisible2.value = false;
}
function addtitle(obj) {
  const d = {
    key: '标题',
    index: obj,
    value: '亿码互联',
    grid: 'w-full',
  };
  if (mode === 'v1') {
    list.mdata.push(d);
  } else if (mode === 'v2') {
    list.push(d);
  }
  listStore.setList(list);
}
function addline(line) {
  const d = {
    key: '分割线',
    value: line,
    grid: 'w-full',
  };
  if (mode === 'v1') {
    list.value.mdata.push(d);
  } else if (mode === 'v2') {
    list.value.push(d);
  }
  listStore.setList(list);
}
function openitem(item) {
  const d = {
    key: '个人信息',

    item: { title: '名片', card: item.id },
    isActive: false,
  };
  qrcode_one(d.item.card).then((res2) => {
    console.log('res222222222222222222222', res2);
    if (res2.data.code == 200) {
      d.item.name = d.item.title;
      d.item.instruction = '';
      d.item.setting = [];
      d.item.value = JSON.parse(res2.data.data.onedata.eqJson);
      if (mode === 'v1') {
        list.value.fdata.push(d);
      } else if (mode === 'v2') {
        list.value.push(d);
      }
      dialogVisible3.value = false;
    }
  });
}
function click(index, item) {
  if (item.title === '名片') {
    console.log('card');
    getQrcodebytype(2).then((res) => {
      console.log('res.data.listdata', res.data.data.listdata);
      cardlist.value = res.data.data.listdata;
      cardlist.value.forEach((item, index) => {
        item.obj = JSON.parse(item.eqJson);
      });
      dialogVisible3.value = true;
    });
  } else {
    const d = {
      index: index,
      key: Formlist.value[index].title,

      item,
      isActive: false,
    };
    d.item.name = d.item.title;
    d.item.instruction = '';
    d.item.setting = [];
    if (item.title === '单选项') {
      d.item.radiolist = [
        {
          name: '选项1',
          disabled: false,
        },
        {
          name: '选项2',
          disabled: false,
        },
      ];
    }
    if (item.title === '多选项') {
      d.item.checkboxlist = [
        {
          name: '选项1',
          disabled: false,
          isActive: false,
        },
        {
          name: '选项2',
          disabled: false,
          isActive: false,
        },
      ];
    }
    if (item.title === '表格') {
      d.item.table = [
        {
          th: '标题1',
          td: '内容1',
        },
        {
          th: '标题2',
          td: '内容2',
        },
      ];
    }
    if (item.title === '自增表格') {
      d.item.table = [
        {
          th: '标题1',
          td: '内容1',
          type: 0,
        },
        {
          th: '标题2',
          td: '内容2',
          type: 0,
        },
      ];
      d.item.max = 3;
    }
    if (item.title === '评价') {
      d.item.count = 5;
      d.item.value = 3;
    }
    if (item.title === '检查项') {
      d.item.list = [
        {
          title: '标题1',
        },
        {
          title: '标题2',
        },
        {
          title: '标题3',
        },
      ];
      d.item.value = [3];
    }
    if (item.title === 'NPS量表') {
      d.item.value = 3;
      d.item.min = '没有可能';
      d.item.max = '极有可能';
    }
    if (item.title === '地址') {
      d.item.city = '';
      d.item.address = '';
    }
    if (item.title === '手机号') {
      d.item.show = false;
    }
    if (item.title === '性别') {
      d.item.radiolist = [
        {
          name: '男',
          disabled: false,
        },
        {
          name: '女',
          disabled: false,
        },
      ];
    }
    if (item.title === '车牌') {
      d.item.show = false;
    }

    console.log('d', d);
    console.log('list', list);
    if (mode === 'v1') {
      list.value.fdata.push(d);
    } else if (mode === 'v2') {
      list.value.push(d);
    }
    listStore.setList(list);
    console.log('list3', list);
    console.table('list', list);
  }
  // uni.showToast({
  //   icon: 'none',
  //   title: `${index}点击了第${item.title}个`,
  // })
}
// function handleChange(file, fileList) { // 文件数量改变
//   filelist.value = fileList

//   return true
// }
function removeFile(file, fileList) {
  console.log(file, fileList);

  filelist.value = filelist.value.filter((item) => !item.name.includes(file.name));
}
</script>
<style>
.selected {
  padding: auto;
  border: 3px #fcca00 solid;
  border-radius: 20px;
}

/* 在el-dialog中tinymce z-index 被太小而被遮挡时要加这两句 */
.tox-tinymce-aux {
  z-index: 99999 !important;
}

.tinymce.ui.FloatPanel {
  z-index: 99;
}
</style>

